/*
   Copyright 2011-2012 gtalent2@gmail.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package messagepane

import (
	"github.com/gtalent/starfish/gfx"
	"github.com/gtalent/starfish/input"
	"github.com/gtalent/starfish/util"
	"strings"
)

type StringMessage struct {
	text          []gfx.Text
	size          util.Size
	pressed       bool
	clickListener func()
}

func NewStringMessage(msg string, font *gfx.Font, click func()) *StringMessage {
	sm := new(StringMessage)
	sm.clickListener = click
	msg = strings.Replace(msg, "\t", " ", -1)
	msg = strings.Replace(msg, "\n", " ", -1)
	words := strings.Split(msg, " ")
	sm.text = make([]gfx.Text, len(words))
	for i, v := range words {
		font.SetColor(gfx.Color{0, 0, 0, 255})
		font.WriteTo(v+" ", &sm.text[i])
	}
	return sm
}

func (me *StringMessage) SetSize(size util.Size) {
	me.size = size
}

func (me *StringMessage) Free() {
	for i, _ := range me.text {
		me.text[i].Free()
	}
}

func (me *StringMessage) MouseButtonPress(e input.MouseEvent) {
	me.pressed = false
	var b util.Bounds
	b.Size = me.size
	if b.ContainsPoint(e.Point) {
		me.pressed = true
	}
}

func (me *StringMessage) MouseButtonRelease(e input.MouseEvent) {
	var b util.Bounds
	b.Size = me.size
	if b.ContainsPoint(e.Point) && me.pressed {
		me.clickListener()
	}
	me.pressed = false
}

func (me *StringMessage) Draw(c *gfx.Canvas) {
	x := 15
	y := 10
	for i, _ := range me.text {
		if x+me.text[i].Width() > me.size.Width {
			x = 10
			y += me.text[i].Height() + (me.text[i].Height() / 3)
		}
		c.DrawText(&me.text[i], x, y)
		x += me.text[i].Width()
	}
}
